<template>
    <input class="upload-input" type="file" ref="uploadInput" value="" :multiple="props.multiple" :accept="props.accept"
        @change="fileChange" :disabled="props.disabled || props.readonly">
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted } from 'vue';
const emit = defineEmits(["changeFile"]);
const props = defineProps({
    disabled: {
        type: Boolean,
        default: false,
    },
    readonly: {
        type: Boolean,
        default: false,
    },
    accept: {
        type: String,
        default: 'image/*'
    },
    multiple: {
        type: Boolean,
        default: true
    },
    uploadFileType: {}
})
const isHover = ref(false);
const uploadInput = ref<any>(null);
onMounted(() => {
    if (uploadInput.value) {
        removeListener();
        addListener();
    }
})
onUnmounted(() => {
    if (uploadInput.value) {
        removeListener();
    }
})
// 添加監聽
function addListener() {
    uploadInput.value.addEventListener("drop", drop, false);
    uploadInput.value.addEventListener("dragleave", dragleave);
    uploadInput.value.addEventListener("dragenter", dragenter);
    uploadInput.value.addEventListener("dragover", dragover);
}
// 移除監聽
function removeListener() {
    uploadInput.value.removeEventListener("drop", drop);
    uploadInput.value.removeEventListener("dragleave", dragleave);
    uploadInput.value.removeEventListener("dragenter", dragenter);
    uploadInput.value.removeEventListener("dragover", dragover);
}
function drop(e: any) {
    e.stopPropagation();
    e.preventDefault();
    isHover.value = false;
    if (e.dataTransfer && e.dataTransfer.files) {
        changeFile(e.dataTransfer.files);
    }
}
function dragleave(e: any) {
    e.stopPropagation();
    e.preventDefault();
    isHover.value = false;
}
function dragenter(e: any) {
    e.stopPropagation();
    e.preventDefault();
    isHover.value = true;
}
function dragover(e: any) {
    e.stopPropagation();
    e.preventDefault();
    isHover.value = true;
}
function fileChange(e: any) {
    if (e.target.files && e.target.files.length) {
        changeFile(e.target.files);
    }
    uploadInput.value.value = "";
}
function changeFile(files:any) {
    for (let file of files) {
        if (validateUploadFileType(file)) {
            emit("changeFile", file);
        } else {
            console.log('类型错误');
        }
    }
}
/**
 * 检测文件类型
 * @param curFileType 
 */
 function validateUploadFileType(file: any) {
    return props.uploadFileType.test(file.name);
}
</script>

<style scoped>
.upload-input {
    width: 100%;
    position: absolute;
    height: 100%;
    top: 0;
    left: 0;
    opacity: 0;
    z-index: 5;
    cursor: pointer;
}
</style>